function initJPushAndRegister() {
    var ajpush = api.require('ajpush');
    if (api.systemType === 'android' || api.systemType === 'ios') {
        ajpush.init(function(ret) {
            ajpush.getRegistrationId(function(ret, err) {
                jPushRegister(ret.id);
            });
        });
    } else {
        ajpush.getRegistrationId(function(ret) {
            jPushRegister(ret.id);
        });
    }
}

function jPushRegister(registrationId) {
    const params = {
        deviceId: api.deviceId,
        systemType: api.systemType,
        registrationId: registrationId
    }
    fnBodyPost(interfaces.jPushRegister, params, function(ret, err) {

    })
}

//统计-app恢复
function onResume() {
    const ajpush = api.require('ajpush');
    ajpush.onResume();
    console.log('JPush onResume');
}

//统计-app暂停
function onPause() {
    const ajpush = api.require('ajpush');
    ajpush.onPause();
    console.log('JPush onPause');
}

function setDarkStatusBar() {
    api.setStatusBarStyle({
        style: 'dark'
    });
}

function setLightStatusBar() {
    api.setStatusBarStyle({
        style: 'light',
    });
}

function toastBottom(msg) {
    if (msg) {
        api.toast({
            msg: msg,
            location: 'bottom'
        });
    }
}

function toastMiddle(msg) {
    if (msg) {
        api.toast({
            msg: msg,
            location: 'middle'
        });
    }
}

function fixStatusBar() {
    return $api.fixStatusBar($api.dom("header"));
}

function fixTabBar() {
    return $api.fixTabBar($api.dom("footer"));
}

//自定义底部上拉滑块
function showToastUp(el, callback, okBtn, cancelBtn) {
    this.timer = undefined;
    this.showPara = null;
    this.prEl = el;
    this.els = document.querySelector(this.prEl);
    var thisEls = this.els;

    if (!this.els) {
        return false;
    }

    this.clickEl = document.querySelector(this.prEl + ' .obg');
    this.cacheEl = document.querySelectorAll(this.prEl + ' .bt');
    this.opacityBtnEl = document.querySelectorAll(this.prEl + ' .cancelBg');
    this.okEl = this.cacheEl[0];
    this.opacityEl = this.opacityBtnEl[0];

    if (okBtn && document.querySelector(okBtn)) {
        this.okEl = document.querySelectorAll(this.prEl + ' ' + okBtn)[0];
    }

    var that = this;
    this.show = function(paras) {
        that.showPara = paras;
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function() {
            thisEls.className = 'cmDownToUpWdg showToastUp animatedToastUp';
        }, 5);
    }

    this.cancel = function() {
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function() {
            thisEls.className = 'cmDownToUpWdg';
        }, 300);
    }

    this.okClose = function() {
        thisEls.className = 'cmDownToUpWdg showToastUp';
        clearTimeout(this.timer);
        that.timer = setTimeout(function() {
            thisEls.className = 'cmDownToUpWdg';
        }, 300);
        callback(thisEls, that.showPara);
    }

    if (this.cacheEl.length == 2) {
        this.cancelBtn = this.cacheEl[1];
        this.cancelBtn && this.cancelBtn.removeEventListener('click', this.cancel, false);
        this.cancelBtn && this.cancelBtn.addEventListener('click', this.cancel, false);
    }

    this.clickEl.removeEventListener('click', this.cancel, false);
    this.okEl && this.okEl.removeEventListener('click', this.okClose, false);
    this.clickEl.addEventListener('click', this.cancel, false);
    this.okEl && this.okEl.addEventListener('click', this.okClose, false);

    this.opacityEl.removeEventListener('click', this.cancel, false);
    this.opacityEl.addEventListener('click', this.cancel, false);

    if (cancelBtn && document.querySelector(cancelBtn)) {
        this.cancelEl = document.querySelectorAll(this.prEl + ' ' + cancelBtn)[0];
        this.cancelEl.removeEventListener('click', this.cancel, false);
        this.cancelEl.addEventListener('click', this.cancel, false);
    }

    return { "cancel": this.cancel, "show": this.show };
}

// 处理日期时间 返回 2020年7月
function handleTime(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '年 ' + M + '月'
}

// 处理日期时间 返回 2020-07
function handleTimeY_M(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '-' + M
}

// 处理日期时间 返回 2020/7/17
function handleTimeYMD(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '/' + M + '/' + D
}

// 处理日期时间 返回 2020-7-17
function handleTimeYMD2(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '-' + M + '-' + D
}

// 处理日期时间 返回 {y:2020,m:11,d:11}
function handleTimeYMobj(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    return { y: Y, m: M, d: D }
}

// 处理日期时间 返回 2020年7月17日 15:10:10
function handleTimeYMDHmSZH(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y + '年' + M + '月' + D + '日' + ' ' + h + ':' + m + ':' + s
}

// 处理日期时间 返回 2020
function handleTimeY(timestamp) {
    if (!timestamp) {
        return ''
    }
    var date = new Date(timestamp);
    Y = date.getFullYear();
    M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
    D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())
    h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours());
    m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
    s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
    return Y
}

function getDateInfo(timestamp) {
    var date = new Date(timestamp);
    return {
        year: date.getFullYear(),
        month: date.getMonth() + 1
    }
}

// 获取年份列表
/**
 *
 * @param {y:2020,m:2} oldYear
 * @param {y:2020,m:11} newYear
 * @param type 0 年 1年月 2年月日
 */
function getYearList(oldYear, newYear, type) {
    var yearList = []
        // 年份列表
    for (var y = oldYear.y; y <= newYear.y; y++) {
        yearList.push({
            id: 1,
            value: y,
            childs: []
        })
    }
    if (type == 1 || type == 2) {
        // 月份列表
        yearList.map(item => {
            if (item.value == oldYear.y && item.value != newYear.y) {
                for (var m = oldYear.m; m <= 12; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else if (item.value == newYear.y && item.value != oldYear.y) {
                for (var m = 1; m <= newYear.m; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else if (item.value == newYear.y && item.value == oldYear.y) {
                for (var m = oldYear.m; m <= newYear.m; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            } else {
                for (var m = 1; m <= 12; m++) {
                    item.childs.push({
                        id: 1,
                        value: m,
                        childs: []
                    })
                }
            }
        })
    }
    if (type == 2) {
        // 天数列表
        yearList.map(item => {
            item.childs.map(it => {
                var day = new Date(item.value, it.value, 0);
                day = day.getDate()
                if (item.value == oldYear.y && it.value == oldYear.m && item.value == newYear.y && it.value == newYear.m) {
                    var D = oldYear.d
                    var DM = newYear.d
                    for (var d = D; d <= DM; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else if (item.value == oldYear.y && it.value == oldYear.m) {
                    var D = oldYear.d
                    for (var d = D; d <= day; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else if (item.value == newYear.y && it.value == newYear.m) {
                    var D = newYear.d
                    for (var d = 1; d <= D; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                } else {
                    for (var d = 1; d <= day; d++) {
                        it.childs.push({
                            id: d,
                            value: d,
                        })
                    }
                }
            })
        })
    }
    return yearList
}

/**
 *
 * @param {'年月日列表'} yearList
 * @param {'2020-10-10'} date
 */
function getDateIndex(yearList, date) {
    var nowY = date.slice(0, 4)
    var nowM = date.slice(5, 7)
    var nowD = date.slice(8)
    var indexY = yearList.findIndex(item => {
        return item.value == nowY
    })
    var itemY = yearList.find(item => {
        return item.value == nowY
    })
    var indexM = itemY.childs.findIndex(item => {
        return item.value == nowM
    })
    var itemM = itemY.childs.find(item => {
        return item.value == nowM
    })
    var indexD = itemM.childs.findIndex(item => {
        return item.value == nowD
    })
    return {
        indexY: indexY,
        indexM: indexM,
        indexD: indexD
    }
}

// 上传身份证
function uploadIDCardImg(callback, params) {
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        buttons: ['拍照', '相册']
    }, function(ret, err) {
        if (ret && (ret.buttonIndex == 1 || ret.buttonIndex == 2)) {
            var resultList = api.hasPermission({
                list: ['camera', 'photos']
            });
            if (!resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['camera', 'photos'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted && ret.list[1].granted) {
                        if (ret.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else if (!resultList[0].granted && resultList[1].granted) {
                api.requestPermission({
                    list: ['camera'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted) {
                        if (ret.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else if (resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['photos'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[1].granted) {
                        if (ret.buttonIndex == 1) {
                            return getIdCardPictureUrl('camera', callback, params);
                        } else if (ret.buttonIndex == 2) {
                            return getIdCardPictureUrl('library', callback, params);
                        }
                    }
                });
            } else {
                if (ret.buttonIndex == 1) {
                    return getIdCardPictureUrl('camera', callback, params);
                } else if (ret.buttonIndex == 2) {
                    return getIdCardPictureUrl('library', callback, params);
                }
            }
        }
    });
}

function getIdCardPictureUrl(sourceType, callback, params) {

    api.getPicture({
        sourceType: sourceType,
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: false,
        quality: 10,
        saveToPhotoAlbum: false
    }, function(ret, err) {
        console.log(JSON.stringify(ret))
        if (ret.data && ret.data.length > 0) {
            //上传bas4图片服务器并返回链接
            var spliceBase64 = ret.base64Data.substring(ret.base64Data.indexOf(',') + 1);

            fnPost(interfaces.USER_MODULE.AUTHORIZATION.UPLOAD_IDCARDPHOTO, Object.assign({
                "imageBase64": spliceBase64,
                "imageType": ""
            }, params), function(res) {
                callback(res);
            })
        }
    });
}

function upImgCommon(callback) {
    api.actionSheet({
        title: '',
        cancelTitle: '取消',
        buttons: ['拍照', '相册']
    }, function(ret, err) {
        if (ret && (ret.buttonIndex == 1 || ret.buttonIndex == 2)) {
            var resultList = api.hasPermission({
                list: ['camera', 'photos']
            });
            if (!resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['camera', 'photos'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted && ret.list[1].granted) {
                        if (ret.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else if (!resultList[0].granted && resultList[1].granted) {
                api.requestPermission({
                    list: ['camera'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[0].granted) {
                        if (ret.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else if (resultList[0].granted && !resultList[1].granted) {
                api.requestPermission({
                    list: ['photos'],
                }, function(ret, err) {
                    if (ret && ret.list && ret.list.length > 0 && ret
                        .list[1].granted) {
                        if (ret.buttonIndex == 1) {
                            return getPictureUrl('camera', callback);
                        } else if (ret.buttonIndex == 2) {
                            return getPictureUrl('library', callback);
                        }
                    }
                });
            } else {
                if (ret.buttonIndex == 1) {
                    return getPictureUrl('camera', callback);
                } else if (ret.buttonIndex == 2) {
                    return getPictureUrl('library', callback);
                }
            }
        }
    });
}

function getPictureUrl(sourceType, callback) {
    api.getPicture({
        sourceType: sourceType,
        encodingType: 'jpg',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: false,
        quality: 10,
        saveToPhotoAlbum: false
    }, function(ret, err) {
        if (ret.data && ret.data.length > 0) {
            //上传bas4图片服务器并返回链接
            var spliceBase64 = ret.base64Data.substring(ret.base64Data.indexOf(',') + 1);
            fnBodyPost(interfaces.CONTENT_MODULE.UPLOAD_IMAGE, {
                base64Image: spliceBase64
            }, function(res) {
                callback(res);
            })
        }
    });
}

// 一键登入
function oneClickLogin(params, callback) {
    //检查当前环境是否支持一键登录
    let aliATAuth = api.require('aliATAuthZiZhu');
    aliATAuth.checkEnvAvailable(function(ret) {
        if (ret.enable) {
            // 支持一键登入
            // 调起授权页面
            aliATAuth.getLoginTokenFullScreen(params, function(ret) {
                api.hideProgress();
                if (ret.resultCode == 600001) {
                    // 600001调起页面成功
                }
                if (ret.resultCode == 600000) {
                    // 600000获取到token
                    // 请求接口
                    var paras = 'accessToken=' + ret.token;
                    // fnGet(interfaces.one_click_login + paras, {}, false, function (data) {
                    //     aliATAuth.hideLoginLoading();
                    //     console.log(JSON.stringify(data));
                    //     if (data.success_type === '1') {
                    //         $api.setStorage('token', data.token)
                    //         $api.setStorage('showAdLoginSuccess', true);
                    //         api.sendEvent({
                    //             name: 'refresh_info'
                    //         });
                    //         // 关闭一键登入页面
                    //         aliATAuth.cancelLoginVC();
                    //     } else {
                    //         // 一键登入失败
                    //         // 关闭一键登入页面,跳转普通登入
                    //         aliATAuth.cancelLoginVC();
                    //         callback('一键登入失败')
                    //     }
                    // })
                    aliATAuth.cancelLoginVC();
                } else if (ret.resultCode == 600002 || ret.resultCode == 600005 || ret.resultCode == 600011 || ret.resultCode == 600015 || ret.resultCode == 600021 || ret.resultCode == 700001) {
                    aliATAuth.cancelLoginVC();
                    // 一键登入失败转普通登录
                    callback('普通登录')
                }
            });
        } else {
            // 不支持一键登入转普通登入
            // api.hideProgress();
            callback('不支持一键登录')
        }
    });
}
/**
 * 高德地图两点间距离计算函数
 * @param  lat  经度
 * @param  lon  纬度
 */

function getDistance(lat1, lon1, lat2, lon2) {
    var radLat1 = (lat1 * Math.PI) / 180; //将角度换算为弧度
    var radLat2 = (lat2 * Math.PI) / 180; //将角度换算为弧度
    var a = radLat1 - radLat2;
    var b = (lon1 * Math.PI) / 180 - (lon2 * Math.PI) / 180;
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(
        Math.sin(b / 2), 2)));
    s = s * 6378137.0; // 取WGS84标准参考椭球中的地球长半径(单位:m)
    //s = Math.round(s * 10000) / 10000; //两点之间距离(保留四位)
    return s; //(单位:m)
}
/**
 * 距离保留两位小数
 */
function distanceEclipse(distance) { 
    distance += ""
    var regex = /([0-9]+).[0-9]*/;
    // var regex = /([0-9]+.[0-9]{2})[0-9]*/;
    return distance.replace(regex, "$1")
}

/**
 * 打开地图导航
 */
// 打开地图
function openMap(location,address){
    var vm = this;
    var systemType = api.systemType;
    var buttons = new Array();
    var amap_installed = false;
    if (systemType == 'ios') {
        var installed = api.appInstalled({
            sync: true,
            appBundle: 'iosamap'
        });
        if (installed) {
            amap_installed = true;
            buttons.push('高德地图');
        }
    } else {
        var installed = api.appInstalled({
            sync: true,
            appBundle: 'com.autonavi.minimap'
        });
        if (installed) {
            amap_installed = true;
            buttons.push('高德地图');
        }
    }
    if (amap_installed == false) {
        api.toast({
            msg: '您没有安装高德地图'
        });
        return false;
    }
    api.actionSheet({
        cancelTitle: '取消',
        buttons: buttons
    }, function (ret, err) {
        var btnIndex = ret.buttonIndex;
        if (btnIndex == 1) {
            if (amap_installed) {
                toGaode(location,address)
            } 
        } 
    });
}

function toGaode(location,address) {
    var lon = location.lon
    var lat = location.lat
    if (api.systemType == 'ios') {
        api.openApp({
            iosUrl: 'iosamap://path?sourceApplication=applicationName&sid=BGVIS1&did=BGVIS2&dlat=' + lat + '&dlon=' + lon + '&dname=' + address + '&dev=0&t=0',
        },function(ret,err){});
    } else {
        api.openApp({
            androidPkg: 'android.intent.action.VIEW' ,
            uri:'amapuri://route/plan/?dlat=' + lat + '&dlon=' + lon + '&dname=' + address + '&dev=0&t=0'
        },function(ret,err){});
    }
}
